package com.data;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

import com.bean.StuCourseBean;
import com.constant.Constant;
import com.net.ClientError;
import com.net.ClientException;
import com.net.RequestParameter;
/**
 * 获取个人课表信息，该函数的请求参数为，请求url连接和请求转发连接
 * [1]<url></url>
 * [2]<referer></referer>
 * [3]<type></type> : 用于判断
 * @author mjh
 *
 */
public final class ScheduleData extends BaseData
{
	private final static String TAG = "schedule_data";
	private ArrayList<StuCourseBean> mCourseList;
	
	@Override
	public void startParse(RequestParameter parameter) throws Exception
	{
		
		Log.i(TAG, "开始获取个人课表");
		
		String url = parameter.getValue("url");
		if(url == null)
			throw new NullPointerException("请求连接url为null");
		
		String referer = parameter.getValue("referer");
		if(referer == null)
			throw new NullPointerException("请求转发referer为null");
		
		final String name = parameter.getValue("name");
		
		String stream = openConnection(url, referer, name);
		if(stream == null)
			return;
		String type = parameter.getValue("type");
		if(type != null && type.equals("教师"))
		{
			jsReadStream(stream);
		}
		else
		{
			readStream(stream);
		}
		//System.out.println(stream);
		
	} // startPase
	
	private String openConnection(final String urls, final String referer, final String name) throws Exception
	{
		
		//String ddString = ;
		//URL url = new URL(URLEncoder.encode(urls, "utf-8"));
		URL url = new URL(urls.replaceAll(name, URLEncoder.encode(name, "utf-8")));
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setUseCaches(false);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", referer);
		connection.setRequestProperty("Host", "jwc.xhu.edu.cn");
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent"));
		connection.connect();
		
		if(connection.getResponseCode() != 200)
		{
			Log.i(TAG, "网络请求错误, 错误代码：" + connection.getResponseCode());
			
			throw new ClientException(connection.getResponseCode() +"", ClientError.ERROR_CONNECTION);
		}

		return getWebSource(connection.getInputStream(), "gb2312");
		
//		String[] ul = urls.split("\\?");
//		
//		URL url = new URL(ul[0]);
//		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
//		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
//		connection.setUseCaches(false);
//		connection.setDoOutput(true);
//		connection.setRequestMethod("POST");
//		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
//		connection.setRequestProperty("Referer", referer);
//		connection.setRequestProperty("Host", "jwc.xhu.edu.cn");
//		connection.setRequestProperty("Connection", "Keep-Alive");
//		connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent"));
//		
//		OutputStream out = connection.getOutputStream();
//		out.write(ul[1].getBytes());
//		out.close();
//		
//		connection.connect();
//		
//		if(connection.getResponseCode() != 200)
//		{
//			Log.i(TAG, "网络请求错误, 错误代码：" + connection.getResponseCode());
//			
//			throw new ClientException("网络请求失败", ClientError.ERROR_CONNECTION);
//		}
//
//		return getWebSource(connection.getInputStream(), "gb2312");
		
	} // openConnection
	
	/**
	 * 解析课表数据，课表数据格式如下：
		<table id="Table1" class="blacktab" bordercolor="Black" border="0" width="100%"> 
		 <tbody>
		  <tr> 标题  </tr>
		  <tr> 早晨  </tr>
		  <tr> 
		   <td rowspan="4" width="1%">上午</td>
		   <td width="1%">第1节</td>
		   <td align="Center" width="7%">&nbsp;</td>
		   <td align="Center" width="7%">&nbsp;</td>
		   <td align="Center" width="7%">&nbsp;</td>
		   <td align="Center" width="7%">&nbsp;</td>
		   <td align="Center" rowspan="2" width="7%">应用统计<br />周五第1,2节{第1-12周}<br />郑鹏社<br />5B-302多媒体64座<br /><br /><font color="red">(停0010)</font></td>
		   <td class="noprint" align="Center" width="7%">&nbsp;</td>
		   <td class="noprint" align="Center" width="7%">&nbsp;</td> 
		  </tr>
		  <tr> 没有作用  </tr>
		  <tr> 
		   <td>第3节</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td class="noprint" align="Center">&nbsp;</td>
		   <td class="noprint" align="Center">&nbsp;</td> 
		  </tr>
		  <tr> 没有作用  </tr>
		  <tr> 
		   <td rowspan="4" width="1%">下午</td>
		   <td>第5节</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center" rowspan="2">应用统计<br />周二第5,6节{第1-12周}<br />郑鹏社<br />4A-205普通教室98座</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td class="noprint" align="Center">&nbsp;</td>
		   <td class="noprint" align="Center">&nbsp;</td> 
		  </tr>
		  <tr> 没有作用  </tr>
		  <tr> 
		   <td>第7节</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center" rowspan="2">形势与政策<br />周三第7,8节{第1-6周}<br />罗世韡<br />4A-302多媒体160座</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td class="noprint" align="Center">&nbsp;</td>
		   <td class="noprint" align="Center">&nbsp;</td> 
		  </tr>
		  <tr> 没有作用  </tr>
		  <tr> 
		   <td rowspan="3" width="1%">晚上</td>
		   <td>第9节</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td align="Center">&nbsp;</td>
		   <td class="noprint" align="Center">&nbsp;</td>
		   <td class="noprint" align="Center">&nbsp;</td> 
		  </tr>
		  <tr> 没有作用	  <tr> 
		  <tr> 没有作用	  </tr> 
		 </tbody>
		</table>
	 * @param stream
	 */
	private void readStream(final String stream) throws Exception
	{
		Document document = Jsoup.parse(stream);
		Element table = document.getElementById("Table1");
		//System.out.println(table.html().toString());
		
		mCourseList = new ArrayList<StuCourseBean>();
		// <tbody>
		Elements trs = table.select("tr");
		// 跳过标题和早读
		for(int i = 2, lenght = trs.size(); i < lenght - 2; i += 2)
		{
			Element tr = trs.get(i);
			// 获取到第一个节点
			Element td = tr.child(0);
			// 跳过上午，下午，晚上节点
			if(i == 2 || i == 6 || i == 10)
				td = td.nextElementSibling();

			// 跳过第几节
			td = td.nextElementSibling();
			int j = 0;
			while(td != null)
			{
				StuCourseBean bean = new StuCourseBean();
				StuCourseBean bean1 = new StuCourseBean();
				bean.x = (i - 1) / 2;
				bean.y = j;
				bean1.x = (i - 1) / 2;
				bean1.y = j;
				String text = td.ownText().trim();
				
				if(text != null)
				{
					String array[] = text.split(" ");
					if(array.length >= 3)
					{
						bean.name = array[0];
						bean.time = array[1];
						bean.teacher = array[2];
						bean.site = array[3];
					}
					/*if(array.length >= 3)
					{
						bean.name = array[0];
						bean.time = array[1];
						bean.teacher = array[2];
						bean.site = array[3];
						if(array.length>=7){
							bean1.name = array[4];
							bean1.time = array[5];
							bean1.teacher = array[6];
							bean1.site = array[7];
						}
					}*/
				}
				mCourseList.add(bean);
				/*if(bean1.name!=null){
					mCourseList.add(bean1);
				}*/
				// 下一次操作
				j = j + 1;
				td = td.nextElementSibling();
			} // while(td != null)
			
		} // for(..)
		
		Log.i(TAG, "获取课表数据成功");
	} // readStream
	
	
	private void jsReadStream(final String stream)
	{
		Document document = Jsoup.parse(stream);
		Element table = document.getElementById("Table6");
		if(table == null)
			return;
		
		Elements trs = table.select("tr");
		if( trs == null )
			return;
		mCourseList = new ArrayList<StuCourseBean>();
		// 跳过早读和标题
		for ( int i = 2, len = trs.size(); i < len - 2; i +=  2 )
		{
			Element tr = trs.get(i);
			// 获取到第一个节点
			Element td = tr.child(0);
			
			// 跳过上午，下午，晚上节点
			if(i == 2 || i == 6 || i == 10)
				td = td.nextElementSibling();

			// 跳过第几节
			td = td.nextElementSibling();
			int j = 0;
			while(td != null)
			{
				StuCourseBean bean = new StuCourseBean();
				bean.x = (i - 1) / 2;
				bean.y = j;
				String text = td.ownText().trim();
				
				if(text != null)
				{
					String array[] = text.split(" ");
					if(array.length >= 3)
					{
						bean.name = array[0];
						bean.time = array[1];
						bean.teacher = array[2];
						bean.site = array[3];
						if(array.length >= 4)
							bean.more = array[4];
					}
					
				}
				mCourseList.add(bean);
				// 下一次操作
				j = j + 1;
				td = td.nextElementSibling();
			} // while(td != null)
			
		} // for ( ... )
		
	} // jsReadStream
	
	
	public ArrayList<StuCourseBean> getCourseList()
	{
		return mCourseList;
	}
	 
	public void printData()
	{
		for(int i = 0; i < mCourseList.size(); i++)
		{
			StuCourseBean bean = mCourseList.get(i);
			System.out.println(bean.x);
			System.out.println(bean.y);
			System.out.println(" " + bean.name);
			System.out.println(" " + bean.teacher);
			System.out.println(" " + bean.teacher);
			System.out.println(" " + bean.site);
			System.out.println(" " + bean.remark);
		}
	}
	

} // class ScheduleData
